package com.tcp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

/**
 * 1. TCP 服务器端
 */
public class SocketTCP02Client {

    public static void main(String[] args) throws IOException {
        // 1. 链接本机中 9999 端口的应用程序,如果链接成功，那么返回 socket对象
        System.out.println("InetAddress.getLocalHost()＝" +InetAddress.getLocalHost());
        Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
        System.out.println("客户端 socket = " + socket.getClass());

        // 2.连接服务器成功之后，发送数据
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("hello server".getBytes());
        System.out.println("客户端数据发送完毕.......");


        //3.数据发送完毕之后，设置结束标记
        socket.shutdownOutput();

        // 3. 读取 服务器端发送的数据
        InputStream inputStream = socket.getInputStream();
        byte[] buf = new byte[1024];
        int read = 0;
        while ((read = inputStream.read(buf))!=-1){
            // 根据读取到的实际长度，显示内容
            System.out.println(new String(buf , 0 ,read));
        }


        // 4.发送数据之后，必须关闭流，以及 socket
        outputStream.close();
        inputStream.close();
        socket.close();
        System.out.println("客户端退出了........");

    }
}
